package com.example.demo.service;

import com.example.demo.entity.*;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.mapper.LogsMapper;
import com.example.demo.util.RendSMS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    LogsMapper logsMapper;

    /**
     * 用户注册
     * @param customer
     * @return
     */
    @Override
    public JsonResult addCustomer(Customer customer) {
        customer.setInviter(customer.getInvitationCode());
        JsonResult json = new JsonResult();
        boolean b = true;
        Integer num = customerMapper.getJudge(customer.getInviter()) ;

        if(num==0){
            json.setSuccess(false);
            json.setMessage("邀请码错误");
            return json;
        }
        Integer customerNum = customerMapper.getCustomerNum(customer.getPhone());
        if(customerNum==0){
            String verificationCode = customerMapper.getVerificationCode(customer.getPhone());
            if(customer.getVerificationCode().equals(verificationCode)){
                String invitationCode =null;
                //生成邀请码
                while (b){
                    invitationCode = getRandString(6);
                    b = equalStr(invitationCode);
                    continue;
                }
                //将邀请码存入数据库
                customer.setInvitationCode(invitationCode);
                customerMapper.addCustomer(customer);
                //添加钱包
                customerMapper.saveWallet(customer.getPhone(),invitationCode);
                json.setSuccess(true);
                json.setMessage("注册成功");
            }else {
                json.setSuccess(false);
                json.setMessage("验证码错误");
                return json;
            }
            json.setSuccess(true);
            json.setMessage("注册成功");
        }else {
            json.setSuccess(false);
            json.setMessage("账号已存在，请更换");
        }
        return json;
    }

    /**
     * 用户登录
     * @param customer
     * @return
     */
    @Override
    public JsonResult login(Customer customer) {

        JsonResult json = new JsonResult();
        Customer client1 = customerMapper.customerLogin(customer.getPhone());
        if (client1 == null) {
            json.setSuccess(false);
            json.setMessage("用户名不存在请先注册");
        } else {
            if (client1.getPassword().equals(customer.getPassword())) {
                json.setSuccess(true);
                json.setMessage("登录成功");
                Map<String, Object> map = new HashMap<>();
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                map.put("clientId",client1.getId());
                map.put("member",client1.getMember());//0 未认证，1 已认证
                map.put("phone",client1.getPhone());
                map.put("token", token);
                map.put("timestamp", System.currentTimeMillis());
                json.setData(map);
            } else {
                json.setSuccess(false);
                json.setMessage("密码错误，再次输入");
            }
        }
        return json;
    }

    /**
     * 修改密码
     * @param customer
     * @return
     */
    @Override
    public JsonResult upPassword(Customer customer) {
        JsonResult json = new JsonResult();
        Customer client1 = customerMapper.customerLogin(customer.getPhone());
        if (client1.getPassword().equals(customer.getPassword())) {
            try {
                customerMapper.upPassword(customer.getPhone(),customer.getNewPassword());
                json.setSuccess(true);
                json.setMessage("密码更改成功");
            }catch (Exception e){
                e.printStackTrace();
                json.setSuccess(false);
                json.setMessage("系统错误，密码更改失败");
            }
        }else {
            json.setSuccess(false);
            json.setMessage("密码错误");
        }
        return json;
    }

    /**
     * 判断是否认证会员
     * @param phone
     * @return
     */
    @Override
    public Integer judgeState(String phone) {
        return customerMapper.judgeState(phone);
    }

    /**
     /**localhost:6080/customer/startWork?phone=15603371683&startTime=2017-08-30 10:00:00
     * 开始工作
     * @param workTable
     * @return
     */
    @Override
    public JsonResult startMemberWork(WorkTable workTable) {
        JsonResult json = new JsonResult();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        workTable.setStartTime(sd.format(date));
        workTable.setUpdateTime(sd.format(date));
        //同时在两个平行表中生成开始数据（表1记录总的数据，表2记录临时数据）
        //todo 首先确认表一中是否拥有未完成的订单
        String tableCode = customerMapper.getTableCode(workTable.getPhone());
        if(null==tableCode){
            workTable.setTableCode("WORK"+sdf.format(date));
            //todo 记录表1插入数据
            //开始时间
            customerMapper.startMemberWork(workTable);
            //todo 临时表表2插入数据
            customerMapper.startMemberWorkSubtabulation(workTable);
            customerMapper.endAllLogsWork(workTable.getPhone());
            customerMapper.saveWorkLogs(workTable);
        }else {
            //todo 临时表表2插入数据
            workTable.setTableCode(tableCode);
            customerMapper.startMemberWorkSubtabulationw(workTable);
            customerMapper.endAllLogsWork(workTable.getPhone());
            customerMapper.saveWorkLogs(workTable);
        }
        json.setSuccess(true);
        json.setMessage("开始工作");
        return json;
    }
    @Override
    @Transactional
    public JsonResult startNoMemberWork(WorkTable workTable) {
        JsonResult json = new JsonResult();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        workTable.setStartTime(sd.format(date));
        workTable.setUpdateTime(sd.format(date));
        //同时在两个平行表中生成开始数据（表1记录总的数据，表2记录临时数据）
        //todo 首先确认表一中是否拥有未完成的订单
        String tableCode = customerMapper.getNoMemberTableCode(workTable.getPhone());
        if(null==tableCode){
            workTable.setTableCode("WORK"+sdf.format(date));
            //todo 记录表1插入数据
            //开始时间
            //todo 临时表表2插入数据
            customerMapper.startNoMemberWork2(workTable);
            customerMapper.endAllLogsWork(workTable.getPhone());
            customerMapper.saveWorkLogs(workTable);
        }else {
            //todo 临时表表2插入数据
            workTable.setTableCode(tableCode);
            customerMapper.startNoMemberWorkSubtabulation(workTable);
            customerMapper.endAllLogsWork(workTable.getPhone());
            customerMapper.saveWorkLogs(workTable);
        }
        json.setSuccess(true);
        json.setMessage("开始工作");
        return json;
    }
    /**
     * 进入页面前进行判断，是否还有工作未完成
     * @param phone
     * @return
     */
    @Override
    public JsonResult loginMemberJudge(String phone) {
        JsonResult json = new JsonResult();
        Map<String,Object> map = new HashMap<>();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer time = customerMapper.getTimework1(phone);
        //当执行时间大于可执行时间时
        if(time!=null&&time>=12*3600){
            customerMapper.endWorkMember(phone);
        }
        //todo 查询是否存在有为完成12小时工作时间的订单

        WorkTable workTable = customerMapper.getWorkTable1(phone);
        if (workTable==null){
            //todo 查询工作的结束时间，如果不超过10小时，不能进行
//            long miao = (new Date(System.currentTimeMillis())).getTime();
            long miao = date.getTime();
            Date endTime = customerMapper.getEndTime(phone);
            if (endTime != null&&(miao-endTime.getTime())/1000<10*60*60) {
                map.put("is_have",1);
                map.put("allowTime",(10*60*60-(miao-endTime.getTime())/1000));
                map.put("msg","结束没有超过10小时，请10小时后再工作，还剩"+(10*60*60-(miao-endTime.getTime())/1000));
            } else {
                map.put("is_have",2);
                map.put("allowTime", 12*3600);
                map.put("msg","还没有开始工作！！");
            }
        }else {
            //查询是否有正在运行的订单
            WorkTable workTable1 = customerMapper.getWorkTableIng(phone);
            if(workTable1==null){
                map.put("is_have",3);
                map.put("allowTime", 12*3600-workTable.getAllTime());
                map.put("workedMoney",workTable.getEarnMoney());
                map.put("msg","已开始开始工作！！还剩余"+(12*3600-workTable.getAllTime())+"秒试运行时间");
            }else {
                map.put("is_have",4);
                map.put("allowTime", 12*3600-workTable.getAllTime());
                map.put("WorkTable",workTable1);
                map.put("workedMoney",workTable1.getEarnMoney());
                map.put("msg","订单正在进行");
            }
        }
        json.setData(map);
        json.setSuccess(true);
        return json;
    }
    @Override
    @Transactional
    public JsonResult loginNoMemberJudge(String phone) {
        JsonResult json = new JsonResult();
        Map<String,Object> map = new HashMap<>();
        BaseInfo baseInfo = customerMapper.getBaseInfo();
        //查询是否订单有已完成的订单
        Integer count = customerMapper.getOverOrder(phone);
        if(count!=null&&count>=1200){
            map.put("is_have",1);
            map.put("allowTime",0);
            map.put("msg","非认证用户可试用20分钟,认证后可永久使用");
        }else {
            //todo 查询是否存在有未完成20分钟工作时间的订单
            WorkTable workTable = customerMapper.getSubtabulation1(phone);
            if (workTable==null){
                map.put("is_have",2);
                map.put("allowTime",20*60);
                map.put("msg","还没有开始工作！！");
            }else {
                //查询是否有正在运行的订单
                WorkTable workTable1 = customerMapper.getSubtabulationIng(phone);
                if(workTable1==null){
                    map.put("is_have",3);
                    map.put("allowTime",20*60-workTable.getAllTime());
                    map.put("workedMoney",workTable.getEarnMoney());
                    map.put("msg","已开始开始工作！！还剩余"+(20*60-workTable.getAllTime())+"秒试运行时间");
                }else {
                    if(workTable1.getAllTime()>1200){
                        workTable1.setAllTime(1200);
                        customerMapper.endNoMemberWorkm(workTable1);
//                            customerMapper.endNoMemberWork3(workTable1);
                    }else {
                        map.put("is_have",4);
                        map.put("allowTime",20*60-workTable1.getAllTime());
                        map.put("WorkTable",workTable);
                        map.put("workedMoney",workTable.getEarnMoney());
                        map.put("msg","订单正在进行");
                    }
                }
            }
        }
        json.setData(map);
        json.setSuccess(true);
        return json;
    }

    /**
     * 更新工作
     * @return
     */
    @Override
    @Transactional
    public JsonResult updateNoMemberWork(WorkLogs workLogs) {
        JsonResult json = new JsonResult();
        customerMapper.updateNoMemberWorklog(workLogs);
        //更新钱包
        customerMapper.updateAWalletlogs(workLogs);
        customerMapper.updateWorkNoLogs(workLogs);
        logsMapper.insertWorkLogs(workLogs);
        json.setSuccess(true);
        json.setData(workLogs.getActualAmount());
        json.setMessage("更新成功");
        return json;
    }

    /**
     * 结束工作
     * @param workTable
     * @return
     */
    @Override
    public JsonResult endMemberWork(WorkTable workTable) {
        JsonResult json = new JsonResult();
        WorkTable workTable1 = customerMapper.getWorkTable(workTable.getPhone());
//        workTable1.setEarnMoney(workTable1.getEarnMoney()+workTable.getEarnMoney());
        Date date = new Date();
        Date now = new Date(System.currentTimeMillis());
        Date start = customerMapper.getUpdateTime(workTable.getPhone());
        if(start==null){
            json.setSuccess(false);
            return json;
        }
        long startTime = start.getTime();
        long nowTime = now.getTime();
        long allTime = (nowTime-startTime)/1000;
        workTable.setAllTime(Integer.valueOf(String.valueOf(allTime)));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        workTable1.setEndTime(sdf.format(date));
        workTable1.setAllTime((int) allTime+workTable1.getAllTime());
        customerMapper.endMemberWork1(workTable);
        //todo 同时更新主表
        customerMapper.endMemberWork2(workTable1);//只更新
        json.setSuccess(true);
        json.setMessage("结束工作");
        return json;
    }

    @Override
    @Transactional
    public JsonResult endNoMemberWork(WorkTable workTable) {
        JsonResult json = new JsonResult();
        //查询附表中的数据
        WorkTable workTable1 = customerMapper.getSubtabulationk(workTable.getPhone());
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //计算结束时间
        workTable1.setEndTime(sdf.format(date));
        //结束附表
        customerMapper.endNoMemberWork1(workTable);
        //更新钱包
        customerMapper.updateAWallet(workTable.getPhone(),workTable.getEarnMoney());
        customerMapper.updateWorkLogs(workTable);
        //todo 同时更新主表
        json.setSuccess(true);
        json.setMessage("结束工作");
        return json;
    }

    /**
     * 获取主页的所有数据
     * @param phone
     * @return
     */
    @Override
    public JsonResult main(String phone) {
        Map<String,Object> map = new HashMap<>();
        JsonResult json = new JsonResult();
        Integer member = customerMapper.getMember(phone);
        map.put("is_member",member);
        Integer nowAllMoney = customerMapper.getNowAllMoney(phone);
        map.put("nowAllMoney",nowAllMoney);//当前金额
        Integer allMoney = customerMapper.getAllMoney(phone);
        map.put("allMoney",allMoney);//累计金额
        Integer yesMoney = customerMapper.getYesMoney(phone);
        map.put("yesMoney",yesMoney);
        // 获取 邀请码
        String inv = customerMapper.getInv(phone);
        Integer FirMoney = customerMapper.getFirMoney(inv);
        map.put("firMoney",FirMoney);
        Integer SecMoney = customerMapper.getSecMoney(inv);
        map.put("secMoney",SecMoney);
        Integer ThrMoney = customerMapper.getThrMoney(inv);
        map.put("thrMoney",ThrMoney);
        json.setSuccess(true);
        json.setData(map);
        json.setMessage("获取主页数据成功");
        return json;
    }


    /**
     * 获取个人中心所有数据
     * @param phone
     * @return
     */
    @Override
    public JsonResult personal(String phone) {
        Map<String,Object> map = new HashMap<>();
        JsonResult json = new JsonResult();
        //手机号（用*隐藏中间4位）
        String putPhone =  phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
        map.put("phone",putPhone);
        // 获取 邀请码
        String inv = customerMapper.getInv(phone);
        //查询当前好友人数，确定自己的等级
        Integer levelNow = customerMapper.getLevelNow(inv);
        //更新自己的等级
        customerMapper.updateCustomerLevel(phone,levelNow);
        //用户级别和升级进度条
        LevelSchedule  levelSchedule = customerMapper.getProgressBar(inv);
//        if(levelSchedule.getEnLevel()==null){
//            levelSchedule.setCurrentPeople(0);
//            levelSchedule.setStLevel(0);
//            levelSchedule.setNeedPeople(1);
//            levelSchedule.setEnLevel(1);
//        }
        map.put("levelSchedule",levelSchedule);
        //查询一级好友数
        Integer friFriend = customerMapper.getFirFriend(inv);
        map.put("friFriend",friFriend);
        //查询二级好友数
        Integer secFriend = customerMapper.getSecFriend(inv);
        map.put("secFriend",secFriend);
        //查询三级好友数
        Integer thrFriend = customerMapper.getThrFriend(inv);
        map.put("thrFriend",thrFriend);
        json.setSuccess(true);
        json.setData(map);
        json.setMessage("获取个人中心数据成功");
        return json;
    }

    /**localhost:6080/customer/material?materialType=1
     * 根据类型不同查询视频 1，推广 2，Q&A 3
     * @param materialType
     * @return
     */
    @Override
    public JsonResult material(String materialType) {
        JsonResult json = new JsonResult();
        List<Material> list = customerMapper.getMaterial(materialType);
        json.setData(list);
        json.setSuccess(true);
        return json;
    }

    /**
     * 提现记录
     * @param phone
     * @return
     */
    @Override
    public JsonResult withdrawals(String phone) {
        JsonResult json = new JsonResult();
        List<Logs> list = customerMapper.getWithdrawals(phone);
        json.setData(list);
        json.setSuccess(true);
        return json;
    }
    @Override
    public JsonResult isBinding(String phone) {
        JsonResult json = new JsonResult();
        String str = customerMapper.isBinding(phone);
        Integer num = 1;
        if(str!=null){
            num = 1;
        }else {
            num = 0;
        }
        json.setData(num);
        json.setSuccess(true);
        return json;
    }

    /**localhost:6080/customer/verificationCode?phone=18712882023
     * 注册,获取验证码
     * @return
     */
    @Override
    public JsonResult saveVerificationCode(String phone) {
        JsonResult json =new JsonResult();
        RendSMS rendSMS = new RendSMS();
        //todo 查询手机号码是否已注册
        Integer num = customerMapper.selectNum(phone);
        if(num == 0){
            try {
                String verificationCode = rendSMS.getRandNum(6);
                ArrayList kk = rendSMS.sms_api2(phone,verificationCode);
                //todo 查询是否已经获取过验证码
                Integer b = customerMapper.selectCode(phone);
                if(b==0){
                    //如果没有，存储手机号码和验证码
                    customerMapper.saveVerificationCode(phone,verificationCode);
                }else {
                    //如果有，根据手机号更改验证码
                    customerMapper.updateCode(phone,verificationCode);
                }
                json.setSuccess(true);
                json.setMessage("申请成功");
            }catch (Exception e){
                e.printStackTrace();
                json.setSuccess(false);
                json.setMessage("申请失败");
            }
        }else {
            json.setData(-1);
            json.setSuccess(false);
            json.setMessage("该账号已经存在");
        }
        return json;
    }


    private String TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private String APPID = "wx209abb61a1ca312e";
    private String SECRET = "dc6d37977888d62f5aa7dc80eb6c0daa";


    /**
     * 获取微信openID
     * @return
     */
    @Override
    public JsonResult getOpenId(String code,String phone) {
        JsonResult json = new JsonResult();
        String excitCode = customerMapper.getOpenId(phone);
        if(excitCode!=null){
            if(!("").equals(excitCode)){
                json.setMessage("该账号已绑定，不能再次绑定");
                json.setSuccess(false);
                return json;
            }
        }
        try {
            String urlStr ="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid=wxc69b596fd4ff4c0c" +
                    "&secret=3d1752b6f020020e530be5ab49a9eaee" +
                    "&code="+code+
                    "&grant_type=authorization_code";
            URL url = new URL(urlStr);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                System.out.println(line);
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            String openId = "";
            String openIdbg = "";
            String[] str = sb.toString().split(",");
            for (int i=0;i<str.length;i++){
                String str4 = str[3];
                openId = str4.substring(10,str4.length()-1);
                openIdbg = customerMapper.getOpenIdbg(openId);
            }
            if(openIdbg!=null){
                if(!openIdbg.equals("")){
                    json.setMessage("该微信号已绑定其他账号，不能重复绑定");
                    json.setSuccess(false);
                    return json;
                }
            }
            customerMapper.saveOpenId(openId,phone);
            json.setData(openId);
            json.setMessage("绑定成功");
            json.setSuccess(true);
        }catch (Exception e){
            e.printStackTrace();
            json.setMessage("绑定失败");
            json.setSuccess(false);
        }
        return json;
    }

    /**
     * 获取工作每秒的价格区间
     * @return
     */
    @Override
    public JsonResult getSecondEarn() {
        JsonResult json = new JsonResult();
        BaseInfo baseInfo = customerMapper.getBaseInfo();
        Map<String,Object> map = new HashMap<>();
        map.put("memberMax",baseInfo.getEarnPerSecondMaxMember());
        map.put("memberMin",baseInfo.getEarnPerSecondMinMember());
        map.put("noMemberMax",baseInfo.getEarnPerSecondMax());
        map.put("noMemberMin",baseInfo.getEarnPerSecondMin());
        map.put("earnSecondMaxMember",baseInfo.getEarnSecondMaxMember());
        map.put("earnSecondMaxNoMember",baseInfo.getEarnSecondMaxNoMember());
        json.setData(map);
        json.setSuccess(true);
        return json;
    }

    @Override
    public BaseInfo getBaseInfo() {
        return customerMapper.getBaseInfo();
    }

    @Override
    public JsonResult getError(Integer error,String phone) {
        JsonResult json = new JsonResult();
        WorkTable workTable = new WorkTable();
        workTable.setPhone(phone);
        BaseInfo baseInfo = customerMapper.getBaseInfo();
        if(error==0){//失败
            WorkTable workTable1 = customerMapper.getWorkTableIng(workTable.getPhone());
            if(workTable1!=null){
                customerMapper.endMemberWork3(workTable);
                WorkTable workTable3 = customerMapper.getWorkTableEnd(workTable1.getTableCode());
                customerMapper.endMemberWork2(workTable3);
            }
        }else if(error==1){//正常
            //查询出上一次更新的时间
            WorkTable workTable1 = customerMapper.getWorkTable(phone);
            if(workTable1!=null){
                //计算时间长度
                Date now = new Date(System.currentTimeMillis());
                Date start = customerMapper.getUpTime(workTable.getPhone());
                Integer timeuse = customerMapper.getUseTime(workTable.getPhone());
                long startTime = start.getTime();
                long nowTime = now.getTime();
                //未连接的访问时间
                long time = (nowTime-startTime)/1000;
                //判断是否超出12小时
                Integer eleTime = workTable1.getAllTime()+Integer.valueOf(String.valueOf(time));
                if(eleTime>12*3600){
                    //按照12小时计算
                    double max = (12*3600-timeuse) *baseInfo.getEarnPerSecondMaxMember();
                    double min = (12*3600-timeuse) *baseInfo.getEarnPerSecondMinMember();
                    Integer result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
                    Integer earnMoney = result+workTable1.getEarnMoney();
                    workTable1.setEarnMoney(earnMoney);
                    workTable1.setAllTime(12*3600);
                    WorkTable workTable2 = customerMapper.getWorkTableIng(workTable.getPhone());
                    customerMapper.endMemberWork2(workTable1);
                    WorkTable workTable3 = customerMapper.getWorkTableEnd(workTable2.getTableCode());
                    customerMapper.endMemberWorkEnd(workTable3);
                    //todo 求出更新到结束的时间点，存入endTime(非会员也是这样)
                    //更新钱包
                    customerMapper.updateWallet(workTable1.getPhone(),workTable3.getEarnMoney());
                    workTable1.setEarnMoney(result);
                    customerMapper.updateWorkLogsAgain(workTable1);
                }else {
                    //价格区间
                    double max = time*baseInfo.getEarnPerSecondMaxMember();
                    double min = time*baseInfo.getEarnPerSecondMinMember();
                    Integer result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
                    Integer earnMoney = result+workTable1.getEarnMoney();
                    workTable1.setEarnMoney(earnMoney);
                    Date date = new Date();
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    workTable1.setUpdateTime(sd.format(date));
                    workTable1.setAllTime(Integer.valueOf(String.valueOf(time)));
                    customerMapper.updateMemberWorkNormal(workTable1);
                    //更新钱包
                    customerMapper.updateAWallet(workTable1.getPhone(),result);
                    workTable1.setEarnMoney(result);
                    customerMapper.updateWorkLogsAgain(workTable1);
                }
            }
        }
        json.setSuccess(true);
        return json;
    }

    @Override
    @Transactional
    public JsonResult getErrorNoMember(Integer error,String phone) {
        JsonResult json = new JsonResult();
        WorkTable workTable = new WorkTable();
        workTable.setPhone(phone);
        WorkLogs workLogs = new WorkLogs();
        BaseInfo baseInfo = customerMapper.getBaseInfo();
        if(error==0){//失败
            WorkTable workTable1 = customerMapper.getNoMemeberWorkTableIng(workTable.getPhone());
            if(workTable1!=null){
                customerMapper.endNoMemeberWorka(phone);
            }
        }else if(error==1){//正常
            //查询出上一次更新的时间
            WorkTable workTable1 = customerMapper.getNoMemeberWorkTable(phone);
            if(workTable1!=null){
                //计算时间长度
                Date now = new Date(System.currentTimeMillis());
                Date update = customerMapper.getNoMemeberUpTime(workTable.getPhone());
                Integer start = customerMapper.getNoMemeberStartTime(workTable.getPhone());
                if(start==null){
                    json.setSuccess(false);
                    return json;
                }
                long startTime = update.getTime();
                long nowTime = now.getTime();
                //未连接的访问时间(未更新时间)
                long time = (nowTime-startTime)/1000;
                //判断是否超出20分钟
                Integer eleTime = start+Integer.valueOf(String.valueOf(time));
                if(eleTime>1200){
                    //按照20分钟计算
                    double max = (1200-start) *baseInfo.getEarnPerSecondMaxMember();
                    double min = (1200-start) *baseInfo.getEarnPerSecondMinMember();
                    Integer result = Math.abs((int)(min + (int)(Math.random() * ((max - min) + 1))));
                    WorkTable workTable2 = customerMapper.getNoMemeberWorkTableIng(workTable.getPhone());
                    workTable1.setAllTime(1200);
                    workTable1.setEarnMoney(result);
                    customerMapper.endNoMemeberWork2(workTable1);
                    //更新钱包
                    customerMapper.updateWallet(workTable1.getPhone(),result);

                    customerMapper.updateWorkLogsAgain(workTable1);
                }else {
                    //价格区间
                    double max = (nowTime-startTime)/1000*baseInfo.getEarnPerSecondMax();
                    double min = (nowTime-startTime)/1000*baseInfo.getEarnPerSecondMin();
                    Integer result = Math.abs((int)(min + (int)(Math.random() * ((max - min) + 1))));
                    Integer earnMoney = result+workTable1.getEarnMoney();
                    workTable1.setEarnMoney(earnMoney);
                    Date date = new Date();
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    workTable1.setUpdateTime(sd.format(date));
                    workTable1.setAllTime(eleTime);
                    //更新钱包00000000
                    customerMapper.updateAWallet(workTable1.getPhone(),result);
//                    System.out.println(workTable1.getEarnMoney());
                    customerMapper.updateNoMemberWorkNorm(workTable1);
//                    customerMapper.updateNoMemberWorkNorma3(workTable1);
                    workTable1.setEarnMoney(result);
                    customerMapper.updateWorkLogsAgain(workTable1);
                }
            }
        }
        json.setSuccess(true);
        return json;
    }

    /**
     * 获取当前等级可提现金额总数和已提现金额
     * @param phone
     * @return
     */
    @Override
    public JsonResult getAmountLimit(String phone) {
        JsonResult json = new JsonResult();
        Map<String,Object> map = new HashMap<>();
        //当前等级
        Integer level = customerMapper.getLevelByPhone(phone);
        map.put("level",level);//当前等级
        Integer levelMoney = customerMapper.getAllLevelMoney(level);
        map.put("levelMoney",levelMoney);//当前等级对应的所有的钱
        Integer cashTime = customerMapper.getCashTime(phone);
        map.put("cashTime",cashTime);//已提现次数
        Integer allMoney = customerMapper.getAllTimeMoney(phone);
        map.put("allMoney",allMoney);//已提现金额
        Level levelAndMoney = customerMapper.getLevelAndMoney(level);
        map.put("levelAndMoney",levelAndMoney);//每个等级对应的提现金额
        json.setData(map);
        json.setSuccess(true);
        return json;
    }
    @Override
    public Date getStartTime(String phone) {
        return customerMapper.getUpdateTime(phone);
    }
    public Date getUpdateTime(String phone) {
        return customerMapper.getNoMemberUpdateTime(phone);
    }
    /**
     * 用户提取押金
     * @param phone
     * @return
     */
    @Override
    public JsonResult applyRefund(String phone) {
        //查询是否存在申请
        JsonResult json = new JsonResult();
        Integer telephone2 = customerMapper.getPhone2(phone);
        if(telephone2!=0){
            json.setMessage("押金已退还，不能再度申请");
            json.setSuccess(true);
            return json;
        }
        Integer telephone = customerMapper.getPhone(phone);
        if(telephone!=0){
            json.setMessage("申请正在处理中，请耐心等候");
            json.setSuccess(true);
            return json;
        }

        //根据手机号码查询当前用户是否是会员
        Integer member = customerMapper.getMember(phone);
        if(member==1){
            //判断当前用户等级
            Integer grade = customerMapper.getGrade(phone);
            long time = customerMapper.getVipTime(phone).getTime();
            long  now = (new Date(System.currentTimeMillis())).getTime();
            long difference = (now - time)/1000 ;
            if(difference>43200){
                if(grade<4){
                    json.setSuccess(true);
                    json.setMessage("您的当前等级不足4级，不能提取押金");
                }else {
                    Date date = new Date();
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    customerMapper.saveApply(phone,grade,sd.format(date));
                    json.setSuccess(true);
                    json.setMessage("您的请求已提交，请耐心等待");
                }
            }else {
                json.setSuccess(true);
                json.setMessage("认证24小时后可申请退还押金");
            }
        }else {
            json.setSuccess(true);
            json.setMessage("您还没有认证，不能提取押金，请先认证");
        }
        return json;
    }
    /**
     * 判断是否认证会员成功
     * @param phone
     * @return
     */
    @Override
    public JsonResult judgeMember(String phone) {
        JsonResult json = new JsonResult();
        Integer value = customerMapper.getMember(phone);
        json.setSuccess(true);
//        json.setMessage("恭喜你！会员认证成功！！");
        json.setData(value);
        return json;
    }
    /**
     * 轮循通知
     * @return
     */
    @Override
    public JsonResult circularNotification() {
        JsonResult json = new JsonResult();
        List<Logs> list = customerMapper.circularNotification();
        json.setData(list);
        json.setSuccess(true);
        return json;
    }

    /**
     * 会员结束12小时工作
     * @param workTable
     * @return
     */
    @Override
    public JsonResult endAllWork(WorkTable workTable) {
        JsonResult json = new JsonResult();
        customerMapper.endAllWork(workTable);
        json.setSuccess(true);
        json.setMessage("工作结束成功");
        return json;
    }

    /**
     * 非会员结束20分钟工作
     * @param workTable
     * @return
     */
    @Override
    public JsonResult endAllWorkNoMember(WorkTable workTable) {
        JsonResult json = new JsonResult();
        customerMapper.endAllWorkNoMember(workTable);
        json.setSuccess(true);
        json.setMessage("工作结束成功");
        return json;
    }

    @Override
    public String getUrl() {
        return customerMapper.getUrl();
    }


    //生成随机字符串
    public static String getRandString(int length)
    {
        String charList = "0123456789abcdefghijklmnopqrstuvwxyz";
//        String charList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        String rev = "";
        java.util.Random f = new Random();
        for(int i=0;i<length;i++)
        {
            rev += charList.charAt(Math.abs(f.nextInt())%charList.length());
        }
        return rev;
    }

    public static boolean equalStr(String numOrStr){
        boolean flag = true;
        char str = numOrStr.charAt(0);
        for (int i = 0; i < numOrStr.length(); i++) {
            if (str != numOrStr.charAt(i)) {
                flag = false;
                break;
            }
        }
        return flag;
    }
}

